﻿using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace MoBaoPay
{
    public class MD5WithRSA
    {
        /// <summary>
        /// 返回MD5RSA的签名字符串
        /// </summary>
        /// <param name="fileName">pfx证书文件的路径</param>
        /// <param name="password">pfx证书密码</param>
        /// <param name="strData">待签名的字符串</param>
        /// <param name="encoding">字符集</param>
        /// <returns></returns>
        public static string SignData(string fileName, string password, string strData)
        {
            X509Certificate2 objX5092 = new X509Certificate2(fileName, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);

            RSA rsa = objX5092.GetRSAPrivateKey();
            var data = Encoding.UTF8.GetBytes(strData);
            return Convert.ToBase64String(rsa.SignData(data, HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1)); //.Replace("\r\n","");
        }

        /// <summary>
        /// 验证签名
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="strData"></param>
        /// <param name="sign"></param> 
        /// <returns></returns>
        public static bool Verify(string fileName, string strData, string sign)
        {
            X509Certificate2 objX5092 = new X509Certificate2(fileName);

            RSA rsa = objX5092.GetRSAPublicKey();
            return rsa.VerifyData(Encoding.UTF8.GetBytes(strData), Convert.FromBase64String(sign), HashAlgorithmName.MD5, RSASignaturePadding.Pkcs1);
        }
    }
}